import 'package:get/get.dart';
import 'package:speed_random/core/config/app_config.dart';
import 'package:speed_random/core/services/ad_service.dart';
import 'package:speed_random/pages/home/rand_num/logic.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert'; // 引入 json 相关库

import 'state.dart';

class ComResultsLogic extends GetxController {
  final ComResultsState state = ComResultsState();
  var cachekey = '';
  @override
  void onInit() {
    super.onInit();
    cachekey=state.randComArgs.value.cachekey;
    initCache();

    AppConfig.current.adService.showAd(adType: AdType.interstitial,);

  }

  // 初始化缓存
  Future<void> initCache() async {
    final prefs = await SharedPreferences.getInstance();

    // 读取历史记录
    final String? historyJson = prefs.getString(cachekey+'historyNumbers');
    if (historyJson != null) {
      try {
        state.historyNumbers.value = jsonDecode(historyJson);

      } catch (e) {
        print('解析历史记录失败: $e');
      }
    }
  }
  // 清空历史记录
  Future<void> clearHistory() async {
    state.historyNumbers.clear();
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(cachekey+'historyNumbers');
    await prefs.remove(cachekey+'randomNumbers');
    await prefs.remove(cachekey+'randomNumbersSum');
    final RandNumLogic logic = Get.put(RandNumLogic());
    final  statenum =Get.find<RandNumLogic>().state;
    statenum.historyNumbers.value = [];
    statenum.randomNumbers.value = [];
    statenum.randomNumbersSum.value = 0;
    update();
  }


}
